# -*- coding:utf-8 -*-
import requests
import re
import pprint
#添加请求头
HEADERS = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}
def getYoudaoWebByWord(word):
    resp = requests.get('http://dict.youdao.com/w/%s/' % word,headers = HEADERS)
    return resp.text
def getPattern(exp):
    return re.compile(exp)
def getTargetList(exp,content):
    p = re.compile(exp)
    return p.findall(content)

pattern_phonetic = '<span class="phonetic">(.+?)</span>'
pattern_dict = '<div class="trans-container">[ ]*<ul>[ ]*?(<li>.+?</li>)*[ ]*?</ul>'
pattern_dict_addition = '<p class="additional">\\[(.+?)\\]</p>[ ]*?</div>'
pattern_wordgroup = '<span class="contentTitle"><a class="search-js" href=".+?">(.+?)</a></span>[ ]*?(.+?)[ ]*?</p>'

def getWordMean(word):
    html = getYoudaoWebByWord(word).replace('\n','').replace('\t','').replace('\r','')
    #print(getTargetList(pattern_phonetic,html))
    #print(getTargetList(pattern_dict,html))
    #print(getTargetList(pattern_dict_addition,html))
    text = '%s\n%s\n%s\n' % (getTargetList(pattern_phonetic,html),getTargetList(pattern_dict,html),getTargetList(pattern_dict_addition,html))
    wordGroupList = getTargetList(pattern_wordgroup,html)
    for _e,_c in wordGroupList:
        #print('%s-%s' % (_e,_c.replace(' ','')))
        text = '{0}{1:<25}--->{2}\n'.format(text,_e,_c.replace(' ',''))
    return text

if __name__ == '__main__':
    try:
        print(getWordMean('flip'))
    except Exception as ex:
        print('__main__::: ' + str(ex))
    finally:
        pass